<?php
// -----------------------------------------------------------------------------
// include
// -----------------------------------------------------------------------------

include "../config/config.php";
include "../auth.php";
include "../DBManager.php";
include "../resources/parsedown-1.7.4/Parsedown.php";

// -----------------------------------------------------------------------------
// 访问设置
// -----------------------------------------------------------------------------

if(!isset($_GET["id"])) {
    exit("需要传入有效的参数！");
}

$id = $_GET["id"];
$editUrl = "edit.php?id=$id";

// -----------------------------------------------------------------------------
// 数据库相关设置
// -----------------------------------------------------------------------------

$dbPath = "../" . $dbPath; // 不加这行语句的话会报错，提示找不到对应路径
$db = new DBManager("sqlite:" . $dbPath);

// -----------------------------------------------------------------------------
// 时区日期设置
// -----------------------------------------------------------------------------

date_default_timezone_set($region);

// -----------------------------------------------------------------------------
// Markdown parser 设置
// -----------------------------------------------------------------------------

$mp = new Parsedown();

// -----------------------------------------------------------------------------

/**
 * 传入一个日期间隔对象，根据间隔长短不同返回不同的时间字符串
 * 比如，间隔小于一月时，只返回天数，间隔大于一月而小于一年时，返回月数和天数
 */
function formatDate(DateInterval $interval) : string {

    $allDay = $interval->format("%a");
    $year = $interval->format("%y");
    $month = $interval->format("%m");
    $day = $interval->format("%d");

    $str = "";

    if ($allDay == 0) {
        $str = "0天";
    } else {

        if ($year > 0) {
            $str .= $year . "年";
        }

        if ($month > 0) {
            $str .= $month . "月";
        }

        if ($day > 0) {
            $str .= $day . "天";
        } 
    
    }
   
    return $str;

}

// -----------------------------------------------------------------------------
?>
<html lang="zh">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>查看目标</title>
    <link rel="stylesheet" href="../resources/bootstrap-5.2.0-beta1-dist/css/bootstrap.min.css">
    <style>
        a {
            text-decoration: none;
        }
        p, ul, ol {
            margin-bottom: 8px;
        }
    </style>
</head>
<body>

<!-- ----------------------------------------------------------------------- -->

<script src="../resources/bootstrap-5.2.0-beta1-dist/js/bootstrap.min.js"></script>
<script src="../resources/jQuery/jquery-3.5.1.js"></script>
<?php include "../globalNavbar.php"; ?>

<!-- ----------------------------------------------------------------------- -->

<!-- div container start -->
<div class="container container-fluid mt-3 mb-5">

    <!-- 导航栏 开始 -->
    <div class="mt-3">
        <nav style="--bs-breadcrumb-divider: '>';" aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a class="text-decoration-none" href="<?php echo $homepage; ?>">首页</a></li>
                <li class="breadcrumb-item"><a class="text-decoration-none" href="index.php">目标管理</a></li>
                <li class="breadcrumb-item active">查看目标</li>
            </ol>
        </nav>
    </div>
    <!-- 导航栏 结束 -->

    <?php

    // ---------------------------------------------------------------------

    if (!$db->goalExist($id)) {
        exit("读取数据失败，因为这个 id 对应的目标不存在。");
    }

    $goalInfor = $db->getGoalInfor($id);

    // ---------------------------------------------------------------------

    $weekDay = ["日","一","二","三","四","五","六"];

    // ---------------------------------------------------------------------

    // 目标描述

    $description = $mp->text($goalInfor["description"]);

    echo <<<BBB
        <div class="card mt-2">

            <div class="card-header d-flex">
                <div class="w-100 big">
                    目标描述
                </div>
                <div class="flex-shrink-0">
                    <a href="$editUrl" target="_self" class="badge text-bg-danger text-decoration-none">编辑(i)</a>
                </div>
            </div> 

            <div class="card-body">
                $description
            </div>

        </div>
    BBB;

    // ---------------------------------------------------------------------

    // 目标状态

    $status = $goalInfor["status"];
    $statusStr = "";

    switch ($status) {
        case "ongoing":
            $statusStr = "进行中";
            break;
        case "waiting":
            $statusStr = "未进行";
            break;
        case "achieved":
            $statusStr = "已完成";
            break;
        case "abandoned":
            $statusStr = "已放弃";
            break;
        default:
            // 系统功能完整的情况下，不会触发这个选项。
            // 开发测试阶段，才有可能触发这个选项。
            $statusStr = "未选择";
    }

    echo <<<BBB
        <div class="card mt-2">

            <div class="card-header bg-light">目标状态</div>

            <div class="card-body">
                <p class="card-text">$statusStr</p>
            </div>

        </div>
    BBB;

    // ---------------------------------------------------------------------

    //
    // 貌似没有必要显示出来
    //$createTime = $goalInfor["createTime"];
    //$week = date("w", $createTime);
    //$createTime = date("Y年m月d日", $createTime);
    //$createTime .= "，周" . $weekDay["$week"];

    // ---------------------------------------------------------------------

    // 生命周期

    // 开始日期
    $startDate = $goalInfor["startDate"];
    $week = date("w", strtotime($startDate));
    $startDate = date("Y年m月d日", strtotime($startDate));
    $startDate .= "，周" . $weekDay["$week"];

    // 结束日期
    $endDate = $goalInfor["endDate"];
    $week = date("w", strtotime($endDate));
    $endDate = date("Y年m月d日", strtotime($endDate));
    $endDate .= "，周" . $weekDay["$week"];

    $DTIToday = new DateTimeImmutable("today");
    $DTIStartDate = new DateTimeImmutable($goalInfor["startDate"]);
    $DTIEndDate = new DateTimeImmutable($goalInfor["endDate"]);

    $today = $DTIToday->format("Y年m月d日，周");
    $week = date("w", time());
    $today .= $weekDay["$week"];

    // 已过去的天数
    // 今日日期 - 开始日期 = 已过去的天数
    $passedDays = formatDate($DTIStartDate->diff($DTIToday));

    // 剩余天数
    // 结束日期 - 今日日期 = 剩余天数

    $remainingDays = "";

    // 判断是否逾期，如果是，显示已经逾期
    if ($status == "ongoing" && $DTIToday->diff($DTIEndDate)->format("%R") == "-") {

        $interval = formatDate($DTIToday->diff($DTIEndDate));

        $remainingDays = <<<BBB
            <span class="text-danger">已逾期{$interval}！</span>
        BBB;

    } else {

        if ($DTIToday->diff($DTIEndDate)->format("%R") == "-") {

            $remainingDays = "已过去" . formatDate($DTIToday->diff($DTIEndDate));

        } else {

            $remainingDays = "还剩下" . formatDate($DTIToday->diff($DTIEndDate)) . "（除今日）";

        }

    }

    // 总历时天数
    // 结束日期 - 开始日期 = 总历时天数

    $goalLifeDays = formatDate($DTIStartDate->diff($DTIEndDate));

    echo <<<BBB
        <div class="card mt-2">

            <div class="card-header bg-light">生命周期</div>

            <div class="card-body">
                <p class="card-text"><span class="text-info">开始日期</span>：{$startDate}。已过去{$passedDays} + 1天(开始那天)。</p>
                <p class="card-text"><span class="text-info">结束日期</span>：{$endDate}。{$remainingDays}。</p>
                <p class="card-text">今日日期：{$today}。</p>
                <p class="card-text">历时：{$goalLifeDays} + 1天（开始那天）。</p>
            </div>

        </div>
    BBB;

    // ---------------------------------------------------------------------

    // 奋斗动力
    if (!empty($goalInfor["motivation"])) {
        $motivation = $mp->text($goalInfor["motivation"]);
        echo <<<BBB
            <div class="card mt-2">

                <div class="card-header bg-light">奋斗动力</div>

                <div class="card-body">
                    $motivation
                </div>

            </div>
        BBB;
    } else {
        echo <<<BBB
            <div class="card mt-2">

                <div class="card-header bg-light">奋斗动力</div>

                <div class="card-body">
                    <p class="card-text">你还没有找到「坚持这个目标的动力」，<span class="text-danger">这可能导致你「中途放弃这个目标」</span>！请尽快完善。</p>
                </div>

            </div>
        BBB;
    }

    // ---------------------------------------------------------------------

    // 行动计划
    if (!empty($goalInfor["actionPlan"])) {
        $actionPlan = $mp->text($goalInfor["actionPlan"]);
        echo <<<BBB
            <div class="card mt-2">
                <div class="card-header bg-light">行动计划</div>
                <div class="card-body">
                    $actionPlan
                </div>
            </div>
        BBB;
    } else {
        echo <<<BBB
            <div class="card mt-2">
                <div class="card-header bg-light">行动计划</div>
                <div class="card-body">
                    <p class="card-text">你还没有制定「具体到每年、每月、每周、每日的行动计划」，<span class="text-danger">这可能导致「目标久久无法实现」</span>！请尽快完善。</p>
                    <p class="card-text">「具体到每日的行动计划」应该尽量控制在 15-25 分钟内，任务越容易完成，也就越容易得到执行，越容易坚持下去。古人曾说：</p>
                    <ul>
                        <li>苟有恒，何必三更眠五更起；最无益，莫过一日曝十日寒。</li>
                        <li>图难于其易，为大于其细；天下难事，必作于易；天下大事，必作于细。</li>
                    </ul>
                </div>
            </div>
        BBB;
    }

    // ---------------------------------------------------------------------

    // 备注信息

    if (!empty($goalInfor["remark"])) {
        $remark = $mp->text($goalInfor["remark"]);
        echo <<<BBB
            <div class="card mt-2">

                <div class="card-header bg-light">备注信息</div>

                <div class="card-body">
                    $remark
                </div>

            </div>
        BBB;
    }

    // ---------------------------------------------------------------------

    // 实现日期

    if ($status == "achieved" && !empty($goalInfor["achieveDate"])) {

        $achieveDate = $goalInfor["achieveDate"];
        $DTIAchievedDate = new DateTimeImmutable($achieveDate);

        $week = date("w", strtotime($achieveDate));
        $achieveDate = date("Y年m月d日", strtotime($achieveDate));
        $achieveDate .= "，周" . $weekDay["$week"];

        // 实际历时
        $actualGoalLifeDays = formatDate($DTIStartDate->diff($DTIAchievedDate));

        echo <<<BBB
            <div class="card mt-2">

                <div class="card-header bg-light">实现日期</div>

                <div class="card-body">
                    <p class="card-text">开始于{$startDate}。计划历时{$goalLifeDays} + 1天（开始那天）。</p>
                    <p class="card-text"><span class="text-info">实现于</span>{$achieveDate}。<span class="text-info">实际历时</span>{$actualGoalLifeDays} + 1天（开始那天）。</p>
                </div>

            </div>
        BBB;

    }

    // ---------------------------------------------------------------------

    // 放弃日期
    if ($status == "abandoned" && !empty($goalInfor["giveupDate"])) {

        $giveupDate = $goalInfor["giveupDate"];
        $week = date("w", strtotime($giveupDate));
        $giveupDate = date("Y年m月d日", strtotime($giveupDate));
        $giveupDate .= "，周" . $weekDay["$week"];

        echo <<<BBB
            <div class="card mt-2">
                <div class="card-header bg-light">放弃日期</div>
                <div class="card-body">
                    <p class="card-text">$giveupDate</p>
                </div>
            </div>
        BBB;
    }

    // ---------------------------------------------------------------------

    // 放弃原因
    if ($status == "abandoned") {
        if (!empty($goalInfor["giveupReason"])) {
            $giveupReason = $mp->text($goalInfor["giveupReason"]);
            echo <<<BBB
                <div class="card mt-2">
                    <div class="card-header bg-light">放弃原因</div>
                    <div class="card-body">
                        $giveupReason
                    </div>
                </div>
            BBB;
        } else {
            echo <<<BBB
                <div class="card mt-2">
                    <div class="card-header bg-light">放弃原因</div>
                    <div class="card-body">
                        <p class="card-text text-danger">未填写。</p>
                    </div>
                </div>
            BBB;
        }
        
    }

    // ---------------------------------------------------------------------

    ?>

</div>
<!-- div container end -->

<!-- ----------------------------------------------------------------------- -->

<script src="../resources/jQuery/jquery-3.5.1.js"></script>

<!-- ----------------------------------------------------------------------- -->

<!-- 添加「返回顶部按钮」 -->
<script src="../resources/vanilla-back-to-top/index.js"></script>
<script src="../resources/vanilla-back-to-top/config.js"></script>

<!-- ----------------------------------------------------------------------- -->

<script>

    // 快捷键
    var keyGPressed = 0;
    $(window).keydown(function(event){

        switch (event.key) {
            case "i":
                // 进入编辑
                keyGPressed = 0;
                var url = "<?php echo $editUrl; ?>";
                window.open(url, "_self");
                break
            case "g":
                // 返回顶部
                if (keyGPressed == 1) {
                    $("html, body").animate({ scrollTop: 0});
                    keyGPressed = 0
                } else {
                    keyGPressed = 1
                }
                break
            case "j":
                keyGPressed = 0;
                // 屏幕向下滚动一小段距离
                var y = $(window).scrollTop();
                $('html, body').animate({ scrollTop: y + 650})
                break;
            case "k":
                keyGPressed = 0;
                // 屏幕向上滚动一小段距离
                var y = $(window).scrollTop();
                $('html, body').animate({ scrollTop: y - 650})
                break;
            default:
                keyGPressed = 0;
                break;
        }

        // 滚动到屏幕底部
        if (event.shiftKey) {
            switch (event.key) {
                case 'G':
                    keyGPressed = 0;
                    $("html, body").animate({ scrollTop: $(document).height() }, 1000);
                    break
            }
        }

    })

</script>

<!-- ----------------------------------------------------------------------- -->

</body>
</html>
